// import 'babel-polyfill';
import axios from 'axios';
import router from '@/router'
import { Message } from 'element-ui';

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 `0`
let axiosInstance = axios.create();
// let axiosNoToken = axios.create();
// interceptors 添加请求拦截器

axiosInstance.interceptors.request.use(
  config => {
    let userInfo = sessionStorage.getItem('userInfo');
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      config.headers.token = `${userInfo.token}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// 添加响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    console.log(response)
    if(response.data.code==500){
      Message.error(response.data.msg)
    }else{
      console.log(response.data.result)
     
      return response;
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面
          sessionStorage.removeItem('userInfo');
          router.replace({
            path: 'login',
            query: { redirect: router.currentRoute.fullPath }
          });
          return Promise.reject('token失效，请重新登录');
        case 404:
          return Promise.reject('网络错误，请检查网络连接或联系维护人员');
        case 504:
          return Promise.reject('连接服务器失败');
        default:
          return Promise.reject('');
      }
    }


    //console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    //return Promise.reject(error);
  }
);

let base = '/ep';

export { base, axiosInstance};
